package controllers;

import forms.OwnerDomainForm;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import models.OwnerDomainModel;

import data.OwnerDomainData;

public class VerifyDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {

		TreeMap check = new TreeMap();
		String username = request.getUserPrincipal().getName();
		
		String domain = (String) request.getParameter("domain");
		
		OwnerDomainData oData = new OwnerDomainData();
		OwnerDomainModel ownerDomain = new OwnerDomainModel();
		ownerDomain.setDomain(domain);
		ownerDomain.setUsername(username);
		ownerDomain.setId();
		ownerDomain = oData.getOwnerDomain(ownerDomain.getId());
		
		if (ownerDomain == null) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		
		request.setAttribute("ownerDomain", ownerDomain);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/pages/verify_domain.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String username = request.getUserPrincipal().getName();
		String domain = (String) request.getParameter("domain");
		
		OwnerDomainData oData = new OwnerDomainData();
		OwnerDomainModel ownerDomain = new OwnerDomainModel();
		ownerDomain.setDomain(domain);
		ownerDomain.setUsername(username);
		ownerDomain.setId();
		ownerDomain = oData.getOwnerDomain(ownerDomain.getId());
		
		if (ownerDomain == null) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		
		OwnerDomainForm oForm = new OwnerDomainForm();
		TreeMap form = oForm.checkVerify(request, ownerDomain);
		TreeMap check = (TreeMap) form.get("checkValid");
		ownerDomain = (OwnerDomainModel) form.get("ownerDomain");
		
		if (check.size() == 0) {
			ownerDomain.setStatus(1);
			ownerDomain.setLastUpdate(new Date());
			oData.insert(ownerDomain);
			response.sendRedirect("/profile/view");
			return;
		}
		
		request.setAttribute("ownerDomain", ownerDomain);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/pages/verify_domain.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
}
